package com.zhentao.controller;

import com.zhentao.config.TokenUtil1;
import okhttp3.*;
import okhttp3.RequestBody;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("face")
public class FaceController {

    private static final OkHttpClient client = new OkHttpClient().newBuilder()
            .readTimeout(300, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build();

    /**
     * 人脸对比接口
     * @param img1Base64 第一张图片的Base64编码
     * @param img2Base64 第二张图片的Base64编码
     * @return 对比结果JSON
     */
    @PostMapping("/compare")
    public String compareFaces(@RequestParam String img1Base64, 
                              @RequestParam String img2Base64) {
        try {
            // 1. 获取token
            String apiKey = "uJwxkU0uupwbjYkkCA4PXe28";
            String secretKey = "tn2rln1sFmMY3L5b0I1UY8Z0ehyUgOtg";
            String token = TokenUtil1.getAccessToken(apiKey, secretKey);

            // 2. 调用对比接口
            String result = compareFacesInternal(token, img1Base64, img2Base64);
            
            // 3. 解析并返回结果
            JSONObject json = new JSONObject(result);
            if (json.getInt("error_code") == 0) {
                double score = json.getJSONObject("result").getDouble("score");
                JSONObject response = new JSONObject();
                response.put("success", true);
                response.put("score", score);
                response.put("message", "对比成功");
                response.put("threshold", 80);
                response.put("isMatch", score >= 80);
                return response.toString();
            } else {
                JSONObject response = new JSONObject();
                response.put("success", false);
                response.put("error_code", json.getInt("error_code"));
                response.put("error_msg", json.getString("error_msg"));
                return response.toString();
            }
        } catch (Exception e) {
            JSONObject response = new JSONObject();
            response.put("success", false);
            response.put("error", "人脸对比失败: " + e.getMessage());
            return response.toString();
        }
    }

    /**
     * 文件上传人脸对比接口
     * @param file1 第一张图片文件
     * @param file2 第二张图片文件
     * @return 对比结果JSON
     */
    @PostMapping("/compare-files")
    public String compareFacesWithFiles(@RequestParam("file1") MultipartFile file1,
                                       @RequestParam("file2") MultipartFile file2) {
        try {
            // 1. 将文件转换为Base64
            String img1Base64 = java.util.Base64.getEncoder().encodeToString(file1.getBytes());
            String img2Base64 = java.util.Base64.getEncoder().encodeToString(file2.getBytes());

            // 2. 调用对比接口
            return compareFaces(img1Base64, img2Base64);
        } catch (Exception e) {
            JSONObject response = new JSONObject();
            response.put("success", false);
            response.put("error", "文件处理失败: " + e.getMessage());
            return response.toString();
        }
    }

    /**
     * 获取人脸对比阈值建议
     * @return 阈值建议信息
     */
    @GetMapping("/threshold-info")
    public String getThresholdInfo() {
        JSONObject response = new JSONObject();
        response.put("suggested_threshold", 80);
        response.put("description", "建议阈值为80分，分数越高表示两张人脸越相似");
        response.put("score_range", "0-100");
        response.put("high_confidence", ">= 80分表示高置信度匹配");
        response.put("medium_confidence", "60-79分表示中等置信度");
        response.put("low_confidence", "< 60分表示低置信度");
        return response.toString();
    }

    /**
     * 内部人脸对比方法
     * @param token 访问令牌
     * @param img1Base64 第一张图片Base64
     * @param img2Base64 第二张图片Base64
     * @return 对比结果
     * @throws IOException 网络异常
     */
    private String compareFacesInternal(String token, String img1Base64, String img2Base64) throws IOException {
        // 请求地址
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/match";
        
        // 请求体（JSON格式，包含两张人脸）
        String jsonBody = "[{\"image\":\"" + img1Base64 + "\",\"image_type\":\"BASE64\"},"
                + "{\"image\":\"" + img2Base64 + "\",\"image_type\":\"BASE64\"}]";

        RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody);
        Request request = new Request.Builder()
                .url(url + "?access_token=" + token)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code() + " " + response.message());
            }
            return response.body().string();
        }
    }
}
